﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using PdfSharp;
using PdfSharp.Pdf;
using PdfSharp.Fonts;
using PdfSharp.Drawing;
using PdfSharp.Internal;
using System.Diagnostics;

public partial class Operator_AddContract : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Operator"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
        string creditRequestId = null;
        if (Session["requestId"] != null)
        {
            creditRequestId = Session["requestId"].ToString();
        }
        if (creditRequestId != null)
        {
            var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
            CreditRequest creditRequest = requests.First();
            switch (creditRequest.CreditFacilitiesFormId)
            {
                case 1:
                    BankAccountNumberLabel.Visible = false;
                    BankAccountNumber.Visible = false;
                    break;
                case 2:
                    var bankAccounts = from bankAccountCompany in db.BankAccountCompanies
                                       where bankAccountCompany.CompanyId == creditRequest.UserProfile.CompanyId
                                           && bankAccountCompany.BankAccount.CurrencyId == creditRequest.CurrencyId
                                       select bankAccountCompany;
                    if (bankAccounts.Count() == 0)
                    {
                        OpenNeedBankAccountButton.Visible = true;
                        AddContractButton.Enabled = false;
                    }
                    else
                    {
                        BankAccountNumber.Text = bankAccounts.First().BankAccountId.ToString();
                    }
                    break;
                case 3:
                    break;
            }
            string clientId = creditRequest.UserProfileId.ToString();
            if (clientId != null)
            {
                var profiles = from profile in db.UserProfiles where profile.ProfileId == Convert.ToInt32(clientId) select profile;
                UserProfile clientProfile = profiles.First();
                CompanyName.Text = clientProfile.Company.CompanyName;
                CompanyName.Enabled = false;
                HeadName.Text = clientProfile.CompanyHead;
                HeadName.Enabled = false;
                CreditList.Enabled = false;
                TermLength.Text = requests.First().TermLength.ToString();
                TermLength.Enabled = false;
                Amount.Text = requests.First().Amount.ToString();
                Amount.Enabled = false;
                CurrencyList.Enabled = false;
            }
        }
    }

    protected void CreditList_DataBound(object sender, EventArgs e)
    {
        string creditRequestId = null;
        if (Session["requestId"] != null)
        {
            creditRequestId = Session["requestId"].ToString();
        }
        if (creditRequestId != null)
        {
            var credit = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request.Credit;
            string creditId = credit.First().CreditID.ToString();
            if (creditId != null)
            {
                CreditList.Items.FindByValue(creditId).Selected = true;
            }
        }
    }

    protected void CurrencyList_DataBound(object sender, EventArgs e)
    {
        string creditRequestId = null;
        if (Session["requestId"] != null)
        {
            creditRequestId = Session["requestId"].ToString();
        }
        if (creditRequestId != null)
        {
            var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
            CurrencyList.Items.FindByValue(requests.First().CurrencyId.ToString()).Selected = true;
        }
    }
    protected void RejectButton_Click(object sender, EventArgs e)
    {
        string creditRequestId = null;
        if (Session["requestId"] != null)
        {
            creditRequestId = Session["requestId"].ToString();
        }
        if (creditRequestId != null)
        {
            var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
            requests.First().RequestStatusId = 2;
            db.SubmitChanges();
        }
        Response.Redirect("~/Operator/ApprovedRequests.aspx");
    }

    protected void AddContractButton_Click(object sender, EventArgs e)
    {
        string creditRequestId = null;
        if (Session["requestId"] != null)
        {
            creditRequestId = Session["requestId"].ToString();
        }
        if (creditRequestId != null)
        {
            var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
            CreditRequest creditRequest = requests.First();
            switch (creditRequest.CreditFacilitiesFormId)
            {
                case 2:
                    var userBankAccounts = from bankAccountCompany in db.BankAccountCompanies
                                           where bankAccountCompany.CompanyId == creditRequest.UserProfile.CompanyId
                                               && bankAccountCompany.BankAccount.CurrencyId == creditRequest.CurrencyId
                                               && bankAccountCompany.BankAccountId == Convert.ToInt32(BankAccountNumber.Text)
                                           select bankAccountCompany;
                    if (!getMoneyFromBankAccount())
                    {
                        return;
                    }
                    if (userBankAccounts.Count() > 0)
                    {
                        userBankAccounts.First().BankAccount.Amount += creditRequest.Amount;
                    }
                    else
                    {
                        ErrorLabel.Text = "Неправильный номер счёта.";
                        return;
                    }
                    break;
                case 3:
                    if (!getMoneyFromBankAccount())
                    {
                        return;
                    }
                    break;
            }
            Contract newContract = new Contract();
            newContract.Amount = creditRequest.Amount;
            newContract.CompanyId = creditRequest.UserProfile.CompanyId;
            newContract.CreditId = creditRequest.CreditId;
            newContract.TermLength = creditRequest.TermLength;
            newContract.StatusId = 1;
            newContract.CurrencyId = creditRequest.CurrencyId;
            newContract.CreationDate = DateTime.Now;
            
            double rate = (((creditRequest.Currency.CreditCurrencies.First().Percentage + 100) / 100) / 12);
            decimal monthPay = ((decimal)rate * newContract.Amount) / (decimal)(1 - Math.Pow((1 / (1 + rate)), newContract.TermLength));
            decimal amountPay = monthPay * newContract.TermLength;
            newContract.PayAmount = amountPay;
            db.Contracts.InsertOnSubmit(newContract);
            creditRequest.RequestStatusId = 3;
            creditRequest.UserProfile.HasCredit = true;
            db.SubmitChanges();
        }
        Response.Redirect("~/Operator/ApprovedRequests.aspx");
    }

    protected bool getMoneyFromBankAccount()
    {
        string creditRequestId = null;
        if (Session["requestId"] != null)
        {
            creditRequestId = Session["requestId"].ToString();
        }
        if (creditRequestId != null)
        {
            var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
            CreditRequest creditRequest = requests.First();
            var bankAccounts = from bankAccount in db.BankAccountBanks where bankAccount.BankAccount.CurrencyId == creditRequest.CurrencyId select bankAccount;
            if (bankAccounts.Count() > 0)
            {
                if (bankAccounts.First().BankAccount.Amount > creditRequest.Amount)
                {
                    bankAccounts.First().BankAccount.Amount -= creditRequest.Amount;
                    return true;
                }
                else
                {
                    ErrorLabel.Text = "На банковском счёте недостаточно средств.";
                    return false;
                }
            }
            else
            {
                ErrorLabel.Text = "У банка нет счёта с выбранной валютой.";
                return false;

            }
        }
        return false;
    }

    protected void OpenNeedBankAccountButton_Click(object sender, EventArgs e)
    {
        string creditRequestId = null;
        if (Session["requestId"] != null)
        {
            creditRequestId = Session["requestId"].ToString();
        }
        if (creditRequestId != null)
        {
            var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
            CreditRequest creditRequest = requests.First();
            Session.Add("companyId", creditRequest.UserProfile.CompanyId.ToString());
            Session.Add("currencyId", creditRequest.CurrencyId.ToString());
            Response.Redirect("~/Operator/OpenBankAccount.aspx");
        }
    }

    public PdfDocument PrintToPdf()
    {
        string creditRequestId = null;
        PdfDocument document = null;
        if (Session["requestId"] != null)
        {
            creditRequestId = Session["requestId"].ToString();
        }
        CreditRequest creditRequest = null;
        if (creditRequestId != null)
        {
            var requests = from request in db.CreditRequests where request.CreditRequestId == Convert.ToInt32(creditRequestId) select request;
            creditRequest = requests.First();
        }
        if (creditRequest != null)
        {
            // Create a new PDF document
            document = new PdfDocument();
            document.Info.Title = "Created with PDFsharp";
            document.Language = "Russian";
            // Create an empty page
            PdfPage page = document.AddPage();

            // Get an XGraphics object for drawing
            XGraphics gfx = XGraphics.FromPdfPage(page);

            //XPdfFontOptions options = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);

            // Create a font
            XFont f = new XFont("Arial", 20, XFontStyle.BoldItalic, new XPdfFontOptions(PdfFontEncoding.Unicode));
            XFont font = new XFont("Arial", 16, XFontStyle.BoldItalic, new XPdfFontOptions(PdfFontEncoding.Unicode));
            XFont font1 = new XFont("Arial", 14, XFontStyle.BoldItalic, new XPdfFontOptions(PdfFontEncoding.Unicode));

            // Draw the text
            int pos = 50;
            gfx.DrawString("Информация о кредите", f, XBrushes.Black, 10, pos);
            gfx.DrawString("Кредит: " + creditRequest.Credit.Name, font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Сумма: " + creditRequest.Amount.ToString(), font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Валюта: " + creditRequest.Currency.Name, font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Срок: " + creditRequest.TermLength, font1, XBrushes.Black, 50, pos += 20);

            gfx.DrawString("Информация о клиенте", f, XBrushes.Black, 10, pos += 30);
            gfx.DrawString("Предприятие: " + creditRequest.UserProfile.Company.CompanyName, font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Форма: " + creditRequest.UserProfile.Company.Activity.Name, font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Размер: " + creditRequest.UserProfile.Company.CompanySize.Name, font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Ф.И.О. руководителя: " + creditRequest.UserProfile.CompanyHead, font1, XBrushes.Black, 50, pos += 20);

            gfx.DrawString("Контакты", f, XBrushes.Black, 10, pos += 30);
            gfx.DrawString("Телефон: " + creditRequest.UserProfile.CompanyPhone, font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Телефон руководителя: " + creditRequest.UserProfile.CompanyHeadPhone, font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Адрес: " + creditRequest.UserProfile.Address, font1, XBrushes.Black, 50, pos += 20);
            
            
            gfx.DrawString("Руководитель (" + creditRequest.UserProfile.CompanyHead + "):_____________", font1, XBrushes.Black, 50, pos += 50);
            var oper = from op in db.Operators where op.UserId == (Guid)Membership.GetUser().ProviderUserKey select op;
            gfx.DrawString("Сотрудник банка (" + oper.First().Name + "):_____________", font1, XBrushes.Black, 50, pos += 20);
            gfx.DrawString("Дата: " + DateTime.Now.ToShortDateString(), font1, XBrushes.Black, 50, pos += 30);
        }
        return document;
    }

    protected void PrintButton_Click(object sender, EventArgs e)
    {
        PdfDocument document = PrintToPdf();
        try
        {
            ErrorLabel.Text = "";
            if (document != null)
            {
                AddContractButton.Enabled = true;
                //string filename = "tempfile" + DateTime.Now.ToString() + ".pdf";
                string filename = "tempfile.pdf";
                document.Save(filename);
                Process.Start(filename);
            }
        }
        catch {
            ErrorLabel.Text = "Закройте старую версию контракта";
        }
    }
}